package com.jiang.books.service.jpa;
import javax.persistence.*;

import com.jiang.books.domain.UserGroup;
import com.jiang.books.service.IUserGroupService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
@Transactional
@Service
@Deprecated
public class UserGroupServiceJpa implements IUserGroupService {
    private Log log = LogFactory.getLog(UserGroupServiceJpa.class);

    @PersistenceContext
    public EntityManager em;

    @Override
    @Transactional(readOnly = true)
    public List<UserGroup> findAll() {
        List<UserGroup> ugroups = em.createNamedQuery("UserGroup.findAll", UserGroup.class).getResultList();
        return ugroups;
    }

    @Override
    @Transactional(readOnly = true)
    public UserGroup findById(Long id) {
        TypedQuery<UserGroup> query = em.createNamedQuery("UserGroup.findById", UserGroup.class);
        query.setParameter("id", id);
        return query.getSingleResult();
    }

    @Override
    @Transactional(readOnly = false)
    public UserGroup save(UserGroup ugroup) {
        if (ugroup.getId() == null) {
            log.debug("Inserting new UserGroup");
            em.persist(ugroup);
        } else {
            em.merge(ugroup);
            log.debug("Updating existing UserGroup");
        }
        log.debug("UserGroup saved with id: " + ugroup.getId());
        return ugroup;
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(UserGroup ugroup) {
        UserGroup mergedGroup = em.merge(ugroup);
        em.remove(mergedGroup);
        log.debug("UserGroup with id: " + mergedGroup.getId() + " deleted successfully");
    }

    @Override
    @Transactional(readOnly = true)
    public List<UserGroup> findAllChilderenByNativeQuery(Long id) {
        return em.createNativeQuery(FIND_ALL_CHILDEREN_QUERY, "UserGroupResult").setParameter("id", id).getResultList();
    }

    @Override
    public List<UserGroup> findByGroupName(String groupName) {
        return null;  //ToDo
    }

}